package com.dabao.service.impl;

import com.dabao.bean.Menu;
import com.dabao.query.MenuQuery;
import com.dabao.service.MenuService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dabao on 16/3/4.
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu, MenuQuery> implements MenuService {

    public List<Menu> getMenuTree() {
        List<Menu> menus = dao.selectList(null);
        return menuTree(menus);
    }

    /**
     * 菜单分为一级目录和二级目录
     * 将二级目录的元素放到一级目录的children中
     * @param menus
     * @return
     */
    private List<Menu> menuTree(List<Menu> menus) {
        List<Menu> firstLevels =  new ArrayList<Menu>();

        for(Menu menu : menus) {
            if(menu.getType() == 0) {
                menu.setChildren(new ArrayList<Menu>());
                firstLevels.add(menu);
            }
        }

        for(Menu menu : menus)
            for (Menu firstLevel : firstLevels) {
                if(firstLevel.getId() == menu.getParentId()) {
                    firstLevel.getChildren().add(menu);
                }
            }
        return firstLevels;
    }
}
